#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    udpSocket = new QUdpSocket(this);
    if (!udpSocket->bind(QHostAddress::Any, 8888)) {
        qDebug() << "Failed to bind UDP socket:" << udpSocket->errorString();
    }
    connect(udpSocket, SIGNAL(readyRead()), this, SLOT(recv_data()));
}

Widget::~Widget()
{
    delete ui;
}

void Widget::recv_data()
{
    while (udpSocket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());
        udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
        qDebug() << "Received from" << sender.toString() << ":" << senderPort;
        QString message = QString::fromUtf8(datagram);
        ui->textEdit->append("client: " + message);
    }
}

void Widget::on_pushButton_clicked()
{
    QString message = ui->textEdit->toPlainText();
    if (message.isEmpty()) {
        return;
    }

    QByteArray response = ("Echo: " + message).toUtf8();
    if (udpSocket->writeDatagram(response, sender, senderPort) == -1) {
        qDebug() << "Failed to send datagram:" << udpSocket->errorString();
    } else {
        qDebug() << "Sent to" << sender.toString() << ":" << senderPort;
    }

    //ui->textEdit->clear();
}
